import {ApiHost} from '@/config/common';
import RNFS from 'react-native-fs';
export default async ({token, fileName, file}) => {
  if (!fileName) {
    return {
      code: -1,
      msg: `!fileName`,
    };
  }
  const ossSign = await (async () => {
    let res = undefined;
    try {
      res = await fetch(`${ApiHost}/account/json/get-account-oss-sts`, {
        headers: {
          'content-type': 'application/json',
          token: token,
        },
        method: 'POST',
        body: JSON.stringify({}),
      });
    } catch (e) {
      console.log(`网络异常`, e + '');
    }
    let rsObj = undefined;
    try {
      if (res) {
        rsObj = await res.json();
      }
    } catch (e) {
      rsObj = null;
      console.log(`数据格式异常`, e + '');
    }
    // console.log('签名.rsObj', rsObj);
    return rsObj?.data || null;
  })();

  // console.log('ossSign', ossSign);
  if (!ossSign) {
    return {
      code: -1,
      msg: '获取签名失败',
    };
  }

  const ossRelativePath = `${ossSign.dir}/${fileName}`;
  const postData = {};
  postData.policy = ossSign.policy;
  postData.OSSAccessKeyId = ossSign.accessid;
  postData.signature = ossSign.signature;
  postData['success_action_status'] = 200;
  postData.key = ossRelativePath;
  postData.file = file;

  const postFormData = new FormData();
  for (const key in postData) {
    if (postData[key]) {
      postFormData.append(key, postData[key]);
    }
  }
  let uploadRt = undefined;
  try {
    await fetch(ossSign.host, {
      method: 'POST',
      body: postFormData,
    }).then(async res => {
      if (res.status !== 200) {
        let rtMsg = '';
        try {
          if ((res.status + '').indexOf('403') > -1) {
            rtMsg = '权限不足，非法请求';
          }
        } catch (e) {}
        uploadRt = {
          code: -1,
          msg: rtMsg || '提交失败',
          reason: res,
        };
      } else {
        uploadRt = {
          code: 1,
          msg: '保存成功',
          ossRelativePath,
          res,
        };
      }
    });
  } catch (err) {
    uploadRt = {err};
  }

  return uploadRt;
};
